package com.ppl.server.resources;

import com.github.jmkgreen.morphia.Datastore;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.ppl.server.boot.Boot;
import com.ppl.server.boot.config.Config;
import com.ppl.server.cache.CachingProvider;
import com.ppl.server.messages.UserLoginRequest;
import com.ppl.server.messages.UserLoginResponse;
import com.ppl.server.model.User;
import com.ppl.server.serializers.StringUtil;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import javax.ejb.BeforeCompletion;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Map;
import java.util.UUID;

/**
 * User: Vincent
 * Date: 11/13/12
 * Time: 2:46 PM
 */
@Path("/http/user")
public class LoginAction {
    @Inject
    private Datastore ds;

    @Inject
    private CachingProvider cache;

    Logger LOG = LoggerFactory.getLogger(LoginAction.class);

    @Config("cache.token.length")
    private int defaultTokenLength;

    @Config("cache.token.prefix")
    private String tokenPrefix;

    @PostConstruct
    public void start() {
        Boot.injector.injectMembers(this);
    }

    public Response REJECT(){
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }


    @Path("/doLogin")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response userLogin(UserLoginRequest challenge) {

        if (challenge.isUseSessionToken()) {
            Map<String,String> attributes = challenge.getAttributes();
            if(attributes == null){
                return REJECT();
            }
            String session_id = attributes.get("session_id");
            if(session_id == null){
                return REJECT();
            }
            UserLoginResponse response = cache.get(session_id, UserLoginResponse.class);
            if(response == null){
                return REJECT();
            }

            return Response.ok(response).build();
        }

        User user = ds.createQuery(User.class).filter("name", challenge.getUsername()).filter("password", challenge.getPassword()).get();
        if (user == null) {
            return Response.ok().build();
        }

        UserLoginResponse response = new UserLoginResponse();
        response.setFirstnameOrFullname(user.getFirstnameOrFullname());
        response.setIdentifier(user.getIdentifier());
        response.setLastname(user.getLastName());
        response.setSessionId(StringUtil.generateRandomString(defaultTokenLength, tokenPrefix, false));
        cache.put(response.getSessionId(), response);
        return Response.ok(response).build();
    }


    @Path("/test")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response test() {

        User william = new User();
        william.setId(new ObjectId());
        william.setIdentifier(UUID.randomUUID().toString());
        william.setEmail("email");
        william.setLanguage("zh_cn");
        william.setName("william");
        william.setPassword("william");

        User vincent = new User();
        vincent.setId(new ObjectId());
        vincent.setIdentifier(UUID.randomUUID().toString());
        vincent.setEmail("email");
        vincent.setLanguage("zh_cn");
        vincent.setName("vincent");
        vincent.setPassword("vincent");

        william.setFriendIds(Sets.newHashSet(vincent.getId().toString()));
        vincent.setFriendIds(Sets.newHashSet(william.getId().toString()));

        ds.save(vincent);
        ds.save(william);
        return Response.ok(vincent).build();
    }
}
